const config = require('./config')
const host = config.host

const get = async (url, data, options) => {
  return await request('GET', url, data, options)
}

const post = async (url, data, options) => {
  return await request('POST', url, data, options)
}

const put = async (url, data, options) => {
  return await request('PUT', url, data, options)
}

const del = async (url, data, options) => {
  return await request('DELETE', url, data, options)
}

const request = (method = 'GET', url = '', data = {}, options = {}) => {
  const helper = require('./helper')
  // if (!options.loading) {
  if (options.loading) {
    wx.showLoading()
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: host + url,
      data: data,
      header: { 'content-type': 'application/json' },
      timeout: 10000,
      method: method,
      dataType: 'json',
      success (res) {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          helper.msg(res.data.msg)
          resolve(res.data)
        }
      },
      fail (err) {
        console.log(err)
        helper.msg('request fail')
        reject()
      },
      complete () {
        if (options.loading) {
          wx.hideLoading()
        }
      }
    })
  })
}

module.exports = {
  get, post, put, del
}